import asyncio
import logging
import os

import speedtest
from aiogram import Bot
from fluentogram import TranslatorRunner
from sqlalchemy.ext.asyncio import AsyncSession

from src.infrastructure.db.services.proxy import get_proxy
from src.presentation.tg_bot.services.tg_helpers import broadcast
from src.presentation.tg_bot.worker.exception_handler import exception_handler

logger = logging.getLogger(__name__)


@exception_handler
async def check_proxy_speed_job(
    ctx,
    locale: TranslatorRunner,
    user_id: int,
    proxy_id: int,
):
    bot: Bot = ctx["bot"]
    session: AsyncSession = ctx["session"]

    try:
        proxy = await get_proxy(session, proxy_id)
        logger.info(f"Проверяю скорость работы прокси {proxy}")
        os.environ["HTTP_PROXY"] = f"http://{proxy.login}:{proxy.password}@{proxy.server.ip_address}:{proxy.port_https}"
        os.environ[
            "HTTPS_PROXY"
        ] = f"http://{proxy.login}:{proxy.password}@{proxy.server.ip_address}:{proxy.port_https}"
        os.environ["http_proxy"] = f"http://{proxy.login}:{proxy.password}@{proxy.server.ip_address}:{proxy.port_https}"
        os.environ[
            "https_proxy"
        ] = f"http://{proxy.login}:{proxy.password}@{proxy.server.ip_address}:{proxy.port_https}"

        st = await asyncio.to_thread(speedtest.Speedtest)
        await asyncio.to_thread(st.get_best_server)
        download_speed = round(await asyncio.to_thread(st.download) / 1e6, 2)
        upload_speed = round(await asyncio.to_thread(st.upload) / 1e6, 2)
        await broadcast(
            bot,
            [user_id],
            locale.get(
                "proxy-speed-msg",
                download_speed=download_speed,
                upload_speed=upload_speed,
            ),
        )
    except Exception:
        await broadcast(bot, [user_id], locale.get("speed-check-error"))
